var popupResult = {};
var timeout = null;

function productsearch_open() {
    callService("popup_productsearch", "geths2", {
    }, {
        success : function(result) {
            for (var i = 0; i < result.items.length; i++) {
                jQuery("select[name='hs2']").append(jQuery("<option></option>")
                    .text(result.items[i].name_en)
                    .val(result.items[i].chapter)
                );
            }
        }
    });
    jQuery("select[name='hs2']").change(function() {
        productsearch_hs2changed(jQuery(this).val());
    });

    jQuery("select[name='hs4']").change(function() {
        productsearch_hs4changed(jQuery(this).val());
    });
}

function productsearch_hs2changed(newValue) {
    if (timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    timeout = setTimeout(function() {
        productsearch_refreshHS4(newValue);
    }, 800);
}

function productsearch_hs4changed(newValue) {
}

function productsearch_refreshHS4(newValue) {
    callService("popup_productsearch", "geths4", {
        hs2 : newValue
    }, {
        success : function(result) {
            jQuery("select[name='hs4']").empty();
            for (var i = 0; i < result.items.length; i++) {
                jQuery("select[name='hs4']").append(jQuery("<option></option>")
                    .text(result.items[i].hscode + " - " + result.items[i].description_en + " - " + result.items[i].description_hu)
                    .val(result.items[i].hscode)
                );
            }
        }
    });
}

function submitSearch(btn) {
    var form = jQuery("form[name='productsearchform']").get(0);
    form.submit();
    closePopup();
}
